package com.czy.owner.ui.login;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.MainActivity;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.utils.ActivityHelper;
import com.czy.owner.utils.GetDeviceId;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.MyEditText;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2017/4/28 0028.
 */

public class AccountLoginFragment extends BaseFragment {
    @BindView(R.id.et_login_phone)
    MyEditText etLoginPhone;
    @BindView(R.id.et_login_password)
    MyEditText etLoginPassword;
    protected MyLoadView mLoadView;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        mLoadView = new MyLoadView(getActivity(), "登录中...", true, false);
        etLoginPhone.setText((String) SharedPreferencesUtils.getParam(getActivity(), Constants.SHARED_PREFERENCES_KEY_PHONE, ""));
        etLoginPassword.setText((String) SharedPreferencesUtils.getParam(getActivity(), Constants.SHARED_PREFERENCES_KEY_PASSWORD, ""));
        etLoginPhone.setSelection(etLoginPhone.getText().toString().length());
        etLoginPassword.setSelection(etLoginPassword.getText().toString().length());
    }


    @Override
    protected void updateViews() {

    }


    //忘记密码
    @OnClick(R.id.tv_forget_password)
    public void forgetPassword(View view) {
        startActivity(new Intent(getActivity(), ForgetPasswordActivity.class));
    }

    //注册
    @OnClick(R.id.tv_now_regist)
    public void regist(View view) {
        startActivity(new Intent(getActivity(), RegistActivity.class));
    }

    //登陆
    @OnClick(R.id.btn_now_login)
    public void login(View view) {
        String phone = etLoginPhone.getText().toString().trim();
        String password = etLoginPassword.getText().toString().trim();

        if (!PhoneUtils.isNetworkConnected(getActivity())) {
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.phone_error_null));
            etLoginPhone.requestFocus();
            return;
        }

        if (!PhoneUtils.isMobileNO(phone)) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.phone_error));
            etLoginPhone.requestFocus();
            return;
        }

        if (password.length() < 6 || password.length() > 20) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.input_psd_length));
            etLoginPassword.requestFocus();
            return;
        }


        if ((Build.VERSION.SDK_INT >= 23)) {
            phoneStatePermissions(phone, password);
        } else {
            GetDeviceId getDeviceId = new GetDeviceId(getActivity());
            pid = getDeviceId.getCombinedId();
            MyLog.e("yang", "登陆pid==" + pid);
            loginApi(phone, password);
        }


    }

    public String pid = "";

    public void phoneStatePermissions(final String phone, final String password) {
        Acp.getInstance(getActivity()).request(new AcpOptions.Builder().setPermissions(Manifest.permission.READ_PHONE_STATE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        GetDeviceId getDeviceId = new GetDeviceId(getActivity());
                        pid = getDeviceId.getCombinedId();
                        MyLog.e("yang", "登陆pid==" + pid);
                        loginApi(phone, password);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(getActivity(), "获取手机权限拒绝");

                    }
                });
    }


    private void loginApi(final String phone, final String password) {
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.LOGIN_API);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("password", password);
        params.addBodyParameter("consoleType", "mob");
        params.addBodyParameter("consoleSubType", "androidOwn");
        params.addBodyParameter("pid", pid);
        MyLog.e("yang", params.toString());
        mLoadView.ShowLoadView();
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    String data = JsonUtil.getJsonValuesString(result, "data");
                    UserHelper.getInstance().saveUserAuth(phone, password, true);
                    UserHelper.getInstance().saveUserInfo(getActivity(), data);
                    UserHelper.getInstance().setIsLogined(true);
                    //if (UserHelper.getInstance().getOwnerInfoModel(getActivity()).getBindStoreId() != 0) {
                    MessageHelper.getInstance().reset();
                    EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(getActivity()).getImKey(), UserHelper.getInstance().getUserInfoModel(getActivity()).getImPasswd(), new EMCallBack() {//回调
                        @Override
                        public void onSuccess() {
                            MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getActivity()).getNickName(),
                                    UserHelper.getInstance().getUserInfoModel(getActivity()).getUserLogo());

                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                            MyLog.d("King", "登录聊天服务器成功！");
                            ActivityHelper.getInstance().finishAllActivity();
                            startActivity(new Intent(getActivity(), MainActivity.class));
                            mLoadView.CancleLoadView();


                        }

                        @Override
                        public void onProgress(int progress, String status) {

                        }

                        @Override
                        public void onError(int code, String message) {
                            MyLog.d("King", "登录聊天服务器失败！" + code + "|" + message);
                            ActivityHelper.getInstance().finishAllActivity();
                            startActivity(new Intent(getActivity(), MainActivity.class));
                            mLoadView.CancleLoadView();
                        }
                    });


                    //} else {
                    //startActivity(new Intent(getActivity(), MainActivity.class));
                    //}
                    SharedPreferencesUtils.setParam(getActivity(), Constants.SHARED_PREFERENCES_KEY_PHONE, phone);
                    SharedPreferencesUtils.setParam(getActivity(), Constants.SHARED_PREFERENCES_KEY_PASSWORD, password);
                    //startActivity(new Intent(getActivity(), MainActivity.class));

                } else {
                    mLoadView.CancleLoadView();
                    PhoneUtils.ShowToastMessage(getActivity(), exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.connect_service_error));
                ex.printStackTrace();
                mLoadView.CancleLoadView();
                MyLog.e("yang","ex=="+ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


//    @Override
//    protected boolean isShowBacking() {
//        if (getIntent().getExtras() == null || getIntent().getExtras().getBoolean(Constants.TRANSMISSION_CONTENT_KEY, true)) {
//            return false;
//        } else {
//            return true;
//        }
//    }
}
